package cn.nc.config;


import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Map;


public class ImagesInterceptor extends HandlerInterceptorAdapter {

   @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,
                             Object handler)throws Exception{
       boolean flag = true;
       if(request instanceof MultipartHttpServletRequest){
           MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
           Map<String, MultipartFile> files = multipartRequest.getFileMap();

           Iterator<String> iterator = files.keySet().iterator();

           while(iterator.hasNext()){
               String formKey = (String) iterator.next();
               MultipartFile multipartFile = multipartRequest.getFile(formKey);
               String filename = multipartFile.getOriginalFilename();
//               System.out.println(filename);
               if(!checkFile(filename)){
                    request.setAttribute("errormessage","不支持该类型文件");
                    request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request,response);
                    flag=false;
               }
           }
       }
       return flag;
   }


   private boolean checkFile(String fileName){
       String suffixList ="jpg,gif,png,ico,bmp,jpeg";
       String suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());

       if(suffixList.contains(suffix.trim().toLowerCase())){
           return true;
       }
       return false;
   }

}
